package cn.zyjw.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Slf4j
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    Environment env;

    @Value("#{'${notoken.urls:}'.empty ? null : '${notoken.urls:}'.split(',')}")
    private Set<String> noTokenAccessUrls;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断请求是否需要token访问
        if (allowNotTokenAccess(exchange)) {
            return chain.filter(exchange);
        }
        // 获取token验证
        String token = getToken(exchange);
        if (StringUtils.isBlank(token)) {
            return buildUNAuthorizedResult(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(token);
        if (hasKey == null || !hasKey) {
            return buildUNAuthorizedResult(exchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> buildUNAuthorizedResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "unauthorized");
        jsonObject.put("error_description", "invalid_token");
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }

    private String getToken(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(authorization) || authorization.trim().isEmpty()) {
            return null;
        }
        return authorization.replace("bearer ", "");
    }

    private boolean allowNotTokenAccess(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        return noTokenAccessUrls.contains(path);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
